import moment from 'moment'

export const getAllUrlParam = () => {
  const url = window.location.href
  const urlParams: any = (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (((a as any)[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  )
  return urlParams
}

export const formatTime = (value: any) => {
  if (value == null || value == '') {
    return null
  }
  return moment(value).format('YYYY-MM-DD HH:mm')
}
export const deepFlatten = (arr: any) =>
  [].concat(
    ...arr.map((v: any) => {
      if (Array.isArray(v.children)) {
        const cancheV = JSON.parse(JSON.stringify(v))
        delete cancheV.children
        return deepFlatten(v.children.concat(cancheV))
      }
      return v
    })
  )

export const handleGetItem = (flatItemArr: any, record: any) => {
  return `${flatItemArr.find((item: any) => item.value === record.categoryId1)?.label || '-'}/
      ${flatItemArr.find((item: any) => item.value === record.categoryId2)?.label || '-'}/
      ${flatItemArr.find((item: any) => item.value === record.categoryId3)?.label || '-'}`
}

export const getQueryString = (name: string) => {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}
